<script setup lang="ts">
import CopyOutlined from "@ant-design/icons-vue/CopyOutlined";
import {message, Modal} from "ant-design-vue";
import {WxtBiddingConstraintType, WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";

const props = defineProps({
  value: {
    type: Boolean,
    default: false,
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
  promotionScene: {
    type: String as PropType<WxtBiddingConstraintType>,
    default: WxtBiddingConstraintType.促进全店成交,
  },
  data: {
    type: Array as PropType<any[]>,
    default: () => []
  }
});
const emit = defineEmits([
  "update:value",
  "next",
  "prev",
  "close",
]);
const columns = [
  {
    title: '计划名称',
    dataIndex: 'plan.campaignName',
    width: 240,
  },
  {
    title: '商品标题',
    dataIndex: 'product.title',
    dataType: 'custom',
    slot: 'productTitle',
  },
  ...(props.bizCode === WxtBizCode.关键字推广 ? [{
    title: '关键词数量',
    dataIndex: 'keyword',
    dataType: 'custom',
    slot: 'keywordCount',
    render: (text: any, record: any, index: number) => {
      return '关键词：' + record.requestData.adgroupList[0].wordList.length + '个  ' + '词包：' + record.requestData.adgroupList[0].wordPackageList.length + '个';
    }
  },
    {
      title: '人群数量',
      dataIndex: 'crowd',
      dataType: 'custom',
      slot: 'crowdCount',
      render: (text: any, record: any, index: number) => {
        return record.requestData.adgroupList[0].crowdList.length + '个';
      }
    },
    {
      title: '创意数量',
      dataIndex: 'creative',
      dataType: 'custom',
      slot: 'creativeCount',
      render: (text: any, record: any, index: number) => {
        return record.requestData.adgroupList[0].adgroupOcpc.enableOcpc ? 4 : 0 + '个';
      }
    }] : []),
  {
    title: '添加状态',
    dataType: 'custom',
    slot: 'status',
    align: 'center',
    width: 200,
  }
]
const dataSource = ref<any[]>([]);
const calcDataSource = () => {
  dataSource.value = props.data.filter((item: any) => item.key === 'userConfirm')[0].value;
}
calcDataSource();
const copy = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    message.success('复制成功')
  }).catch(() => {
    message.error('复制失败')
  });
}
const next = () => {
  emit('close');
}
const percent = computed(() => {
  return (dataSource.value.filter(item => item.status >= 2).length / dataSource.value.length * 100).toFixed(2);
})
const startJob = () => {
  message.info('已开始批量添加商品，为了保证添加成功率，添加完成强请勿关闭此页面！',3);
  if (![WxtBizCode.精准人群推广,WxtBizCode.关键字推广].includes(props.bizCode)){
    WxtUtils.customRequest('https://one.alimama.com/material/accessAllowed.json',props.bizCode,{
      itemSelectedMode: "userDefinedItem",
      materialIdList: props.data.filter((item: any) => item.key === 'choiceProduct')[0].value.map((item: any) => {
        return item.itemId;
      }),
      materialType: 1,
      needQualification: true,
      offset: 0,
      optimizeTarget:'conv',
      pageSize: 1000,
      promotionScene: "ad_strategy_laxin",
      promotionType:"item",
      subPromotionType:"item",
      tagId: "1",
    }).then(res=>{
      start();
    })
  }else {
    start();
  }
}
const start = ()=>{
  dataSource.value.forEach((item, index) => {
    setTimeout(() => {
      if (item.status === 0) {
        item.status = 1;
        WxtUtils.customRequest('https://one.alimama.com/adgroup/addList.json', props.bizCode, item.requestData).then((res: any) => {
          if (res.data.info.ok){
            if (res.data.data === null || typeof res.data.data.errorDetails ==='undefined' || res.data.data.errorDetails.length===0) {
              item.status = 2;
            } else {
              item.status = 3;
              item.message = res.data.data.errorDetails[0].msg;
            }
          }else{
            item.status = 3;
            item.message = res.data.info.message;
          }
        })
      }
    }, index * 2000);
  })
}
startJob();
</script>

<template>
  <a-row style="padding-bottom: 10px;">
    <a-space>
      任务执行进度：
      <a-progress :percent="percent" style="width: 300px;" :size="[300, 20]"/>
    </a-space>
  </a-row>

  <base-table table-name="批量添加商品" :columns="columns" :data-source="dataSource" :scroll="{
    y: 500,
  }"
  >
    <template #productTitle="row">
      <a-row type="flex" class="adgroupName" :gutter="5">
        <a-col>
          <a-popover placement="right">
            <template #content>
              <img :src="row.product.imgUrl"
                   style="width: 200px;height: 200px;"
              />
            </template>
            <img :src="row.product.imgUrl"
                 style="width: 60px;height: 60px;border-radius: 5px;"
            />
          </a-popover>
        </a-col>
        <a-col flex="1" class="title">
          <a-tooltip :title="row.product.title">
              <span style="
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;"
              >{{ row.product.title }}</span>
          </a-tooltip>
          <div>
            <a-space>
              <span style="color: #666;">ID: {{ row.product.itemId }}</span>
              <CopyOutlined style="color: #1677ff;cursor: pointer;font-size: 12px;" @click="copy(row.product.itemId)"/>
            </a-space>
          </div>
        </a-col>
      </a-row>
    </template>

    <template #keywordCount="row">
      <a-row type="flex" class="adgroupName" :gutter="5">
        <a-col flex="1" class="title">
          <a-space>
            <a-tooltip :title="(row.requestData.adgroupList[0].wordList||[]).map((i)=>{
              return i.word
            }).join(',')"
            >
              <span style="color: #666;">{{
                  (row.requestData.adgroupList[0].wordList || []).length || 0
                }} 个关键词</span>
            </a-tooltip>
            <a-tooltip :title="(row.requestData.adgroupList[0].wordPackageList||[]).map(i=>{
              return i.wordPackageName;
            }).join(',')"
            >
            <span style="color: #666;"
            >{{
                (row.requestData.adgroupList[0].wordPackageList || []).length || 0
              }} 个词包</span>
            </a-tooltip>
          </a-space>
        </a-col>
      </a-row>
    </template>
    <template #crowdCount="row">
      <a-space>
        <a-tooltip :title="(row.requestData.adgroupList[0].crowdList||[]).map((i)=>{
              return i.crowd.crowdName
            }).join(',')"
        >
              <span style="color: #666;">{{
                  (row.requestData.adgroupList[0].crowdList || []).length || 0
                }} 个人群包</span>
        </a-tooltip>
      </a-space>
    </template>
    <template #creativeCount="row">
              <span style="color: #666;">{{
                  row.requestData.adgroupList[0].adgroupOcpc.enableOcpc ? 4 : 0 + '个'
                }}个创意</span>
    </template>
    <template #status="row">
      <a-space>
        <span type="link" v-if="row.status===0" style="color: #444">等待添加</span>
        <span type="link" v-if="row.status===1" style="color: #07cee5">正在添加</span>
        <span type="link" v-if="row.status===2" style="color: #1677ff">添加成功</span>
        <span type="link" v-if="row.status===3" style="color: #ff4d4f">添加失败</span>

        <a-tooltip v-if="row.status===3" :title="row.message">
          <span type="link" style="color: #ff4d4f">查看详情</span>
        </a-tooltip>
      </a-space>
    </template>
  </base-table>
  <a-divider style="margin-top: 10px;"/>
  <a-row type="flex">
    <a-col flex="1">
    </a-col>
    <a-col>
      <a-space>
        <!--        <a-button @click="emit('prev',[])">上一步</a-button>-->
        <a-button type="default" @click="next">关闭窗口</a-button>
      </a-space>
    </a-col>
    <a-col flex="1">
    </a-col>
  </a-row>
</template>

<style scoped>

</style>
